<template>
    <div class="draw">
        <div class="drawBalance">
            <div class="drawTitle">
                <span>{{ $t("withDrawAmount") }}</span>
            </div>
            <div class="drawNumber">
                <span class="symbol">&yen;</span>
                <input type="number" v-model.number="drawmoney" />
            </div>
            <div class="liner"></div>
            <div class="remain">可用余额：{{ balance }}元</div>
        </div>
        <div class="submit">
            <van-button type="info" :disabled="!drawmoney" @click="submit">
                {{ $t("sureToDraw") }}
            </van-button>
        </div>
    </div>
</template>

<script>
import { Button, Notify } from 'vant';
import 'vant/lib/notify/style/less';

export default {
    name: 'walletdraw',
    components: {
        [Button.name]: Button,
        [Notify.name]: Notify
    },
    data () {
        return {
            drawmoney: undefined,
            balance: this.$store.state.userInfo.balance
        };
    },
    watch: {
        drawmoney (after, before) {
            const interger = after.toString().split('.')[0];
            const decimal = after.toString().split('.')[1];
            if (interger.length > 6) {
                this.drawmoney = before;
                Notify({
                    message: this.$t('errorMessage.maxWithDrawAmount'),
                    type: 'warning'
                });
            }
            if (decimal && decimal.length > 2) {
                this.drawmoney = before;
            }
        }
    },
    methods: {
        submit () {
            this.drawmoney = Math.abs(this.drawmoney);
            if (this.drawmoney > this.balance) {
                Notify({
                    message: this.$t('errorMessage.moreThanAccount'),
                    type: 'danger'
                });
            } else {
                this.$util.loadingToast();
                this.$api.billsApi
                    .createBill({
                        transactionMoney: this.drawmoney,
                        transActionType: 2,
                        users_id: [localStorage.getItem('id'), '5e6d937889f07e4920013759']
                    })
                    .then(result => {
                        if (result) {
                            this.$util.successToast(this.$t('withDrawAmountSuccess'));
                            this.$router.back(-1);
                        } else {
                            // eslint-disable-next-line
                                this.$util.failToast(this.$t("errorMessage.withDrawAmountFailure"));
                        }
                    })
                    .catch(err => {
                        throw err;
                    });
            }
        }
    }
};
</script>

<style scoped lang="less" src="./less/wallet-draw.less"></style>
